import { defineStore } from "pinia";
import { solarPowerSystem } from "@/common/projectAlias";
import api from '@/http/api'
// import store from '@/store'  todo
import router from '@/router'
import { nonRoutes } from '@/router/asyncRoutes.js';

const useUserMessage = defineStore('userMessage', {
  state: () => ({
    userName: '',
    aiSessionId: '',
    mobile: '',
    loginName: '',
    picUrl: '',
    menuMap: [],
    //项目名称
    projectName: '',
  }),
  persist: {
    enabled: true,
    key: 'aiUserMessage',
    storage: sessionStorage,
  },
  getters: {
    //把配置页面的返回做了不返回的定制限制
    getMenuList(state) {
      const menuList = JSON.parse(sessionStorage.aiUserMessage).menuMap
      return state.menuMap || menuList || [];
    },
  },
  actions: {
    setMessage(res) {
      this.userName = res.userName;
      this.aiSessionId = res.sessionId;
      this.mobile = res.mobile;
      this.loginName = res.loginName;
      this.picUrl = res.picUrl;
      this.menuMap = res.menuMap[solarPowerSystem];
      this.projectName = res.projectList.find(project => project.projectAlias === solarPowerSystem)?.projectName
      this.updateRouteList()
    },
    updateRouteList() {
      const menuList = sessionStorage.aiUserMessage ? JSON.parse(sessionStorage.aiUserMessage).menuMap : []
      let menuMap = []
      if (menuList?.length) menuMap = menuList
      if (this.menuMap?.length) menuMap = this.menuMap

      //存储子路由的列表
      let menuChildList = []
      menuMap.map(menu => {
        if (menu.childList) {
          menuChildList.push(...menu.childList)
        } else if (menu.url !== '') {
          menuChildList.push(menu)
        }
      })

      //进行路由拼接
      const routeList = {
        path: '/',
        name: 'index',
        component: () => import('@/common/index/index.vue'),
        children: menuChildList.map(menu => {
          return {
            path: '/' + menu.url,
            name: menu.url,
            meta: {
              title: menu.menuName
            },
            component: () => import(`../views/${menu.url}/index.vue`)
          }
        })
      }
      //注册路由
      router.addRoute(routeList)
    },

    //获取用户信息，用于其他系统跳转
    async getLoginUser() {
      const res = await api.getLoginFun('login/getLoginUser')
      this.setMessage(res)
    },
  },
})

export default useUserMessage